package com.jrfid.smartcabinet.demo.base

import android.app.Application
import androidx.lifecycle.*
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
import androidx.navigation.NavController
import java.lang.RuntimeException
import java.lang.reflect.InvocationTargetException

class BaseViewModelFactory(val application: Application, val navController: NavController) : ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return if (AndroidViewModel::class.java.isAssignableFrom(modelClass)) {
            try {
                modelClass.getConstructor(Application::class.java, NavController::class.java).newInstance(application, navController)
            } catch (e: NoSuchMethodException) {
                throw RuntimeException("Cannot create an instance of $modelClass", e)
            } catch (e: IllegalAccessException) {
                throw RuntimeException("Cannot create an instance of $modelClass", e)
            } catch (e: InstantiationException) {
                throw RuntimeException("Cannot create an instance of $modelClass", e)
            } catch (e: InvocationTargetException) {
                throw RuntimeException("Cannot create an instance of $modelClass", e)
            }
        } else super.create(modelClass)
    }

    public companion object {

        private var sInstance: BaseViewModelFactory? = null

        @JvmStatic
        public fun getInstance(application: Application, navController: NavController): BaseViewModelFactory {
            if (sInstance == null) {
                sInstance = BaseViewModelFactory(application, navController)
            }
            return sInstance!!
        }
    }
}